package com.jumi.microservice.service.invoice.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ExportExcelCommonResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.dto.apiService.OrderGoodsNumNameResponse;
import com.jumi.microservice.dto.invoice.*;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.utils.nuonuo.*;
import com.jumi.microservice.dto.order.GoodsSkuResponse;
import com.jumi.microservice.dto.order.OrderInfoRequest;
import com.jumi.microservice.dto.order.OrderResponse;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.entity.JumiInvoice;
import com.jumi.microservice.entity.JumiInvoiceList;
import com.jumi.microservice.enumerate.InvoiceStatusEnum;
import com.jumi.microservice.exception.InvoiceExceptionEnum;
import com.jumi.microservice.mapper.InvoiceListMapper;
import com.jumi.microservice.mapper.InvoiceMapper;
import com.jumi.microservice.service.*;
import com.jumi.microservice.service.invoice.InvoiceApiService;
import com.jumi.microservice.service.order.OrderServiceImpl;
import com.jumi.microservice.utils.NuoNuoUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InvoiceService {
    private static final Logger log = LoggerFactory.getLogger(InvoiceService.class);
    @Resource
    private InvoiceMapper invoiceMapper;
    @Resource
    private InvoiceListMapper invoiceListMapper;
    @DubboReference
    IAfterService afterService;
    @DubboReference
    IOrderGoodsService iorderGoodsService;
    @Resource
    IOrderDubboService orderDubboService;
    @Resource
    InvoiceApiService invoiceApiService;
    @DubboReference
    IMemberService memberService;
    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private NuoNuoUtil nuoNuoUtil;

    /**
     * 发票列表
     *
     * @param invoiceListRequest
     * @return
     */
    public TableDataInfo<InvoiceListResponse> commentsAdminList(InvoiceListRequest invoiceListRequest) {
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        /*发票状态*/
        if (invoiceListRequest.getInvoiceStatus() != null) {
            queryWrapper.eq("invoice_status", invoiceListRequest.getInvoiceStatus());
        }
        /*查询*/
        if (invoiceListRequest.getHeadType() != null) {
            queryWrapper.eq("head_type", invoiceListRequest.getHeadType());
        }
        if (invoiceListRequest.getSerialNumber() != null) {
            queryWrapper.eq("serial_number", invoiceListRequest.getSerialNumber());
        }
        if (invoiceListRequest.getOrderNum() != null) {
            queryWrapper.eq("order_num", invoiceListRequest.getOrderNum());
        }
        //创建开始时间
        if (invoiceListRequest.getBeginTime() != null && !"".equals(invoiceListRequest.getBeginTime())) {
            queryWrapper.ge("application_time", invoiceListRequest.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //创建结束时间
        if (invoiceListRequest.getEndTime() != null && !"".equals(invoiceListRequest.getEndTime())) {
            queryWrapper.le("application_time", invoiceListRequest.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        }
        IPage<JumiInvoice> jumiInvoicePage = new Page<>(invoiceListRequest.getPageNum(), invoiceListRequest.getPageSize());
        jumiInvoicePage = invoiceMapper.selectPage(jumiInvoicePage, queryWrapper);
        if (jumiInvoicePage.getRecords() == null) {
            return new TableDataInfo<>();
        }
        List<InvoiceListResponse> result = new ArrayList<>();
        for (JumiInvoice invoice : jumiInvoicePage.getRecords()) {
            InvoiceListResponse invoiceListResponse = new InvoiceListResponse();
            BeanUtils.copyProperties(invoice, invoiceListResponse);
            invoiceListResponse.setInvoiceStatusNum(invoice.getInvoiceStatus());
            invoiceListResponse.setInvoiceStatus(EnumUtil.getByCode(invoice.getInvoiceStatus().intValue(), InvoiceStatusEnum.class).getMessage());
            QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
            orderGoodsQueryWrapper.eq("order_no", invoice.getOrderNum());
            List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
            BigDecimal returnCount = orderGoods.stream().map(OrderGoods::getReturnPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            invoiceListResponse.setInvoiceAmount(invoice.getInvoiceAmount());
            invoiceListResponse.setRefundAmount(returnCount);
            result.add(invoiceListResponse);
        }
        TableDataInfo<InvoiceListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(jumiInvoicePage.getTotal());
        return dataInfo;
    }

    /**
     * 开票信息
     *
     * @param invoiceInfoRequest
     * @return
     */
    public InvoiceInfoResponse invoiceInfo(InvoiceInfoRequest invoiceInfoRequest) {
        Integer orderSn = invoiceInfoRequest.getId();
        if (orderSn == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderSn);
        queryWrapper.eq("is_revoke", 0);
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.debug("后端开票信息------【发送订单接口获取后拼接退款金额】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_INFO_ERROR.getMessage());
        }
        /*传递信息*/
        InvoiceInfoResponse invoiceInfoResponse = new InvoiceInfoResponse();
        BeanUtils.copyProperties(invoice, invoiceInfoResponse);
        return invoiceInfoResponse;
    }

    /**
     * 查看发票
     *
     * @param invoiceInfoRequest
     * @return
     */
    public InvoiceViewResponse invoiceView(InvoiceInfoRequest invoiceInfoRequest) {
        Integer orderSn = invoiceInfoRequest.getId();
        if (orderSn == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderSn);
        queryWrapper.eq("is_revoke", 0);
        JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
        log.debug("后端开票信息------【查看发票】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_INFO_ERROR.getMessage());
        }
        /*传递信息*/
        InvoiceViewResponse invoiceViewResponse = new InvoiceViewResponse();
        BeanUtils.copyProperties(invoice, invoiceViewResponse);
        return invoiceViewResponse;
    }

    /**
     * Stat
     * 发票图片更新
     *
     * @param invoiceEditRequest
     * @return
     */
    public Boolean editInvoice(InvoiceEditRequest invoiceEditRequest) {
        QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.lambda().eq(JumiInvoice::getId, invoiceEditRequest.getId());
        JumiInvoice jumiInvoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        if (invoiceEditRequest.getInvoiceType() == 1 && jumiInvoice != null) {
            //普通发票上传
            jumiInvoice.setInvoicePdf(invoiceEditRequest.getInvoicePicture());
            jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.STA_HAS_BILLED.getCode().byteValue());
            int row = invoiceMapper.updateById(jumiInvoice);
            log.info("普通发票上传[{}]", row != 0);
            return row != 0;
        } else if (invoiceEditRequest.getInvoiceType() == 2 && jumiInvoice != null) {
            //冲红发票上传
            jumiInvoice.setRedInvoicePdf(invoiceEditRequest.getInvoicePicture());
            jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.STA_HAS_REDDDMED.getCode().byteValue());
            int row = invoiceMapper.updateById(jumiInvoice);
            log.info("冲红发票发票上传[{}]", row != 0);
            return row != 0;
        }
        return false;
    }

    /**
     * 发票冲红
     *
     * @param invoiceRedRequest
     * @return
     */
    public Boolean invoiceRed(InvoiceRedRequest invoiceRedRequest) {
        boolean result = false;
        Integer invoiceId = invoiceRedRequest.getOrderInvoiceId();
        if (invoiceId == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_RED_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_RED_ERROR.getMessage());
        }
        byte status = 5;
        byte isrevoke = 1;
        invoiceRedRequest.setInvoiceStatus(status);
        invoiceRedRequest.setIsRevoke(isrevoke);
        JumiInvoice invoice = new JumiInvoice();
        BeanUtils.copyProperties(invoiceRedRequest, invoice);
        invoice.setId(invoiceId);
        int row = invoiceMapper.updateById(invoice);
        if (row > 0) {
            //返回 状态
            result = true;
        }
        return result;
    }

    /**
     * ..................................................
     * 发票批量冲红
     *
     * @param invoiceBatchRedRequest
     * @return
     */
    public boolean invoiceBatchRed(InvoiceBatchRedRequest invoiceBatchRedRequest) {
        log.info("后端发票批量冲红------【】:[{}]", JSON.toJSONString(invoiceBatchRedRequest));
        return invoiceMapper.batchUpdata(invoiceBatchRedRequest.getId()) > 0;
    }

    /**
     * 订单发票状态修改
     *
     * @param invoiceStatusRequest
     * @return
     */
    public Boolean invoiceEditStatus(InvoiceStatusRequest invoiceStatusRequest) {
        boolean result = false;
        String invoiceNum = invoiceStatusRequest.getOrderNum();
        if (invoiceNum == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }

        QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.orderByDesc("id");
        invoiceQueryWrapper.eq("order_num", invoiceStatusRequest.getOrderNum());
        invoiceQueryWrapper.eq("is_revoke", 0);
        /*取出最新一条数据*/
        invoiceQueryWrapper.last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        log.info("订单发票状态修改------【取出最新一条数据】:[{}]", JSON.toJSONString(invoice));
        if (invoice != null) {
            invoice.setInvoiceStatus(invoiceStatusRequest.getInvoiceStatus());
            log.info("订单发票状态修改------【invoice】:[{}]", JSON.toJSONString(invoice));
            int row = invoiceMapper.update(invoice, invoiceQueryWrapper);
            log.info("订单发票状态修改------【row】:[{}]", JSON.toJSONString(row));
            if (row > 0) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 根据订单编号查询订单发票状态是否已开票
     *
     * @param invoiceOneRequest
     * @return
     */
    public InvoiceOneResponse invoiceOneStatus(InvoiceOneRequest invoiceOneRequest) {
        String orderSn = invoiceOneRequest.getOrderNum();
        if (orderSn == null) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.orderByDesc("id");
        invoiceQueryWrapper.eq("order_num", orderSn);
        invoiceQueryWrapper.eq("is_revoke", 0);
        /*取出最新一条数据*/
        invoiceQueryWrapper.last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        log.debug("根据订单编号查询订单发票状态是否已开票------【取出最新一条数据】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_ORDER_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_ORDER_ERROR.getMessage());
        }
        /*传递信息*/
        InvoiceOneResponse invoiceOneResponse = new InvoiceOneResponse();
        invoiceOneResponse.setInvoiceStatus(invoice.getInvoiceStatus());
        invoiceOneResponse.setId(invoice.getId());
        return invoiceOneResponse;
    }


    /**
     * 订单发票添加订单列表申请发票++修改订单发票信息时使用
     *
     * @param invoiceAddRequest
     * @return
     */
    public Integer addInvoice(InvoiceAddRequest invoiceAddRequest) {
        /*订单编号申请发票，需要查询改订单是否收货了*/
        Long uid = invoiceAddRequest.getUid();
        if (uid == null || uid.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_NULL.getMessage());
        }
        Byte headType = invoiceAddRequest.getHeadType();
        if (headType == null || headType.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getMessage());
        }
        //判断是申请开票还是修改订单发票：0添加 1修改
        Byte is_insert = 0;
        //订单发票表id
        Integer orderInvoiceId = invoiceAddRequest.getOrderInvoiceId();
        log.info("\n\n\n===============订单发票添加订单列表申请发票------【订单发票表id】:[{}]", JSON.toJSONString(orderInvoiceId));
        if (orderInvoiceId != null) {
            is_insert = 1;
        }
        //订单编号
        String orderNum = invoiceAddRequest.getOrderNum();
        log.info("订单发票添加订单列表申请发票------【订单编号】:[{}]", JSON.toJSONString(orderNum));
        if (orderNum == null || orderNum.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.ORDER_SN_ERROR.getCode(), InvoiceExceptionEnum.ORDER_SN_ERROR.getMessage());
        }
        //查询订单金额开票金额
        OrderInfoRequest orderInfoRequest = new OrderInfoRequest();
        orderInfoRequest.setUid(uid);
        orderInfoRequest.setOrderSn(orderNum);
        TableDataInfo<OrderResponse> orderInfoPage = orderDubboService.getOrderInfoPage(orderInfoRequest);
        log.info("订单发票添加订单列表申请发票------【uid】:[{}]", JSON.toJSONString(uid));
        log.info("订单发票添加订单列表申请发票------【orderInfoPage】:[{}]", JSON.toJSONString(orderInfoPage));
        List<OrderResponse> rows = orderInfoPage.getRows();
        if (rows == null || rows.size() == 0) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_AMOUNT_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_AMOUNT_ERROR.getMessage());
        }
        log.info("订单发票添加订单列表申请发票------【查询订单金额开票金额】:[{}]", JSON.toJSONString(rows));
        Byte orderStatus = rows.get(0).getOrderStatus();//订单状态，4：已收货
        if (orderStatus == null || orderStatus.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_USER_ORDER_STATUS_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_USER_ORDER_STATUS_ERROR.getMessage());
        }
        //计算商品总价加上邮费后的开票金额
//        BigDecimal freightFee = rows.get(0).getFreightFee();
//        log.info("订单发票添加订单列表申请发票------【邮费】:[{}]", JSON.toJSONString(freightFee));
        //BigDecimal orderAmount = rows.get(0).getOrderAmount();
//        BigDecimal orderAmount = rows.get(0).getPayAmount();
//        log.info("订单发票添加订单列表申请发票------【支付费用---包含邮费】:[{}]", JSON.toJSONString(orderAmount));
       /* BigDecimal orderAddAmount = orderAmount.add(freightFee);
        log.info("订单发票添加订单列表申请发票------【加上邮费后的开票金额】:[{}]", JSON.toJSONString(orderAddAmount));*/

        //计算商品总价减去退款金额后的开票金额
        List<GoodsSkuResponse> goodsList = rows.get(0).getGoodsList();
        log.info("订单发票添加订单列表申请发票------【goodsList退款金额】:[{}]", JSON.toJSONString(goodsList));
        BigDecimal total = BigDecimal.ZERO;
        for (GoodsSkuResponse goodsLists : goodsList) {
//            BigDecimal returnPostage = goodsLists.getReturnPostage();
            BigDecimal returnPrice = goodsLists.getReturnPrice();
//            BigDecimal sunReturn = returnPrice.add(returnPostage);
            total = total.add(returnPrice);
            log.info("订单发票添加订单列表申请发票------【total + add】:[{}]", JSON.toJSONString(total));
        }
        log.info("订单发票添加订单列表申请发票------【total总共】:[{}]", JSON.toJSONString(total));
//        BigDecimal subtract = orderAmount.subtract(total);
        BigDecimal subtract = invoiceAddRequest.getInvoiceAmount().subtract(total);
        log.info("订单发票添加订单列表申请发票------【orderAddAmount减去退款金额后的开票金额】:[{}]", JSON.toJSONString(subtract));

        invoiceAddRequest.setInvoiceAmount(subtract);
        /*用户发票抬头id*/
        Integer invoiceId = invoiceAddRequest.getInvoiceId();
        if (invoiceId == null) {
            //添加
            InvoiceAddUserRequest invoiceListAdd = new InvoiceAddUserRequest();
            BeanUtils.copyProperties(invoiceAddRequest, invoiceListAdd);
            Map<String, String> stringStringMap = this.addInvoiceUserList(invoiceListAdd);
            String titleIds = stringStringMap.get("invoiceTitleId");
            log.info("用户发票抬头ID------【返回的抬头ID信息】:[{}]", JSON.toJSONString(stringStringMap));
            if (titleIds == null || titleIds.equals("")) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_HEAD_INSERT_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_UID_HEAD_INSERT_ERROR.getMessage());
            } else {
                log.info("订单发票添加订单列表申请发票------【用户发票抬头id添加】:[{}]", JSON.toJSONString(titleIds));
                Integer titleId = null;
                try {
                    titleId = Integer.parseInt(titleIds);
                } catch (NumberFormatException e) {
                    log.error("订单发票添加订单列表申请发票------【用户发票抬头id添加int类型失败】:[{}]", JSON.toJSONString(titleId));
                    throw new BaseException(InvoiceExceptionEnum.INVOICE_STRING_INT.getCode(), InvoiceExceptionEnum.INVOICE_STRING_INT.getMessage());
                }
                invoiceAddRequest.setInvoiceId(titleId);
            }

        } else {
            //修改
            Byte is_edit = 0;
            //查询该抬头id
            QueryWrapper<JumiInvoiceList> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", invoiceId);
            JumiInvoiceList invoiceListOne = invoiceListMapper.selectOne(queryWrapper);
            log.info("订单发票添加订单列表申请发票------【查询该抬头id】:[{}]", JSON.toJSONString(invoiceListOne));
            if (invoiceListOne == null) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_INVOICE_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_INVOICE_ERROR.getMessage());
            }
            //订单列表申请发票页面提交信息，如果选中设为默认抬头
            Byte isDefault = invoiceAddRequest.getIsDefault();
            if (isDefault == null || isDefault.equals("")) {
                isDefault = 0;
            }
            InvoiceUserListEditRequest invoiceListEdit = new InvoiceUserListEditRequest();
            BeanUtils.copyProperties(invoiceAddRequest, invoiceListEdit);
            invoiceListEdit.setInvoiceTitleId(invoiceAddRequest.getInvoiceId());
            invoiceListEdit.setIsDefault(isDefault);
            ResponseResult<Boolean> booleanResponseResult = this.invoiceEditListUser(invoiceListEdit);
            if (booleanResponseResult.getCode() == 400) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_EDIT_LIST.getCode(), InvoiceExceptionEnum.INVOICE_UID_EDIT_LIST.getMessage());
            }
        }
        //实例类
        int ids = 0;
        JumiInvoice invoice = new JumiInvoice();
        BeanUtils.copyProperties(invoiceAddRequest, invoice);
        //订单为已收货状态，发票状态为，待开票
        byte orderStatusNum = 4;
        if (orderStatus == orderStatusNum) {
            invoice.setInvoiceStatus((byte) 0);
        }
        log.info("订单发票添加订单列表申请发票------【实例类】:[{}]", JSON.toJSONString(invoice));
        if (is_insert == 0) {
            //申请开票，添加
            Integer insert = invoiceMapper.insert(invoice);
            if (insert > 0) {
                /*插入一条数据并返回该数据id，调用实例类自增id*/
                ids = invoice.getId();
            } else {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_INSERT_LIST.getCode(), InvoiceExceptionEnum.INVOICE_UID_INSERT_LIST.getMessage());
            }
            //iOrderService.updateInvoiceId(orderNum,ids);
        } else {
            //修改订单发票信息
            invoice.setId(orderInvoiceId);
            Integer insert = invoiceMapper.updateById(invoice);
            if (insert == 0) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_EDIT_LIST.getCode(), InvoiceExceptionEnum.INVOICE_UID_EDIT_LIST.getMessage());
            }
            ids = orderInvoiceId;
        }
        return ids;
    }

    /**
     * 用户申请发票抬头列表添加
     *
     * @param invoiceAddUserRequest
     * @return
     */
    public Map<String, String> addInvoiceUserList(InvoiceAddUserRequest invoiceAddUserRequest) {
        log.info("用户申请发票抬头列表添加------【invoiceAddUserRequest】:[{}]", JSON.toJSONString(invoiceAddUserRequest));
        Map<String, String> map1 = new HashMap<>();
        //判断是新加抬头还是修改抬头：0添加 1修改
        Byte is_insert = 0;
        Integer invoiceId = invoiceAddUserRequest.getInvoiceId();
        log.info("用户申请发票抬头列表添加------【invoiceId】:[{}]", JSON.toJSONString(invoiceId));
        if (invoiceId != null) {
            is_insert = 1;
        }
        Long uid = invoiceAddUserRequest.getUid();
        if (uid == null || uid.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_NULL.getMessage());
        }
        Byte headType = invoiceAddUserRequest.getHeadType();
        if (headType == null || headType.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_HEAD_TYPE_NULL.getCode(), InvoiceExceptionEnum.INVOICE_HEAD_TYPE_NULL.getMessage());
        }
        String invoiceTitle = invoiceAddUserRequest.getInvoiceTitle();
        if (invoiceTitle == null || invoiceTitle.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getMessage());
        }
        if (headType == 1) {
            String dutyParagraph = invoiceAddUserRequest.getDutyParagraph();
            if (dutyParagraph == null && dutyParagraph.equals("")) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_DUTY_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_DUTY_NULL.getMessage());
            }
        }
        Byte isDefault = invoiceAddUserRequest.getIsDefault();
        if (isDefault == null || isDefault.equals("")) {
            byte isDefaults = 0;
            invoiceAddUserRequest.setIsDefault(isDefaults);
        } else if (isDefault == 1) {
            //查询出该用户该发票类型以前默认选中数据
            QueryWrapper<JumiInvoiceList> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("head_type", headType);
            queryWrapper.eq("is_default", 1);
            JumiInvoiceList invoiceListOne = invoiceListMapper.selectOne(queryWrapper);
            log.info("用户申请发票抬头列表添加------【查询出该用户该发票类型以前默认选中数据】:[{}]", JSON.toJSONString(invoiceListOne));
            if (invoiceListOne != null && !invoiceListOne.getId().equals(invoiceId)) {
                //修改状态为非默认
                invoiceListOne.setIsDefault((byte) 0);
                int row = invoiceListMapper.updateById(invoiceListOne);
                if (row == 0) {
                    throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_ISDEFUALT.getCode(), InvoiceExceptionEnum.INVOICE_UID_ISDEFUALT.getMessage());
                }
            }
        }
        JumiInvoiceList invoiceList = new JumiInvoiceList();
        BeanUtils.copyProperties(invoiceAddUserRequest, invoiceList);
        //设置uid
        invoiceList.setUid(uid.intValue());
        log.info("用户申请发票抬头列表添加------【添加或修改数据】:[{}]", JSON.toJSONString(invoiceList));
        String id = null;
        if (is_insert == 0) {
            int insert = invoiceListMapper.insert(invoiceList);
            try {
                if (insert > 0) {
                    /*插入一条数据并返回该数据id，调用实例类自增id*/
                    id = invoiceList.getId().toString();
                }
            } catch (Exception e) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_USER_TITLE_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_USER_TITLE_ERROR.getMessage());
            }
            log.info("用户发票抬头ID------【添加并返回id】:[{}]", JSON.toJSONString(id));
        } else {
            invoiceList.setId(invoiceId);
            int insert = invoiceListMapper.updateById(invoiceList);
            if (insert == 0) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_TITLE_LIST.getCode(), InvoiceExceptionEnum.INVOICE_UID_TITLE_LIST.getMessage());
            }
            id = invoiceId.toString();
        }
        log.info("用户发票抬头ID------【最终返回的抬头ID】:[{}]", JSON.toJSONString(id));

        map1.put("invoiceTitleId", id);
        map1.put("invoiceTitle", invoiceTitle);
        return map1;

    }

    /**
     * 根据uid 发票抬头类型查询发票列表
     *
     * @param invoiceUserListRequest
     * @return
     */
    public TableDataInfo<InvoiceUserListResponse> invoiceListUser(InvoiceUserListRequest invoiceUserListRequest) {
        TableDataInfo<InvoiceUserListResponse> dataInfo = new TableDataInfo<>();
        Long uid = invoiceUserListRequest.getUid();
        if (uid == null || uid.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_NULL.getMessage());
        }
        Byte headType = invoiceUserListRequest.getHeadType();
        if (headType == null || headType.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getMessage());
        }
        QueryWrapper<JumiInvoiceList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        queryWrapper.eq("head_type", headType);
        queryWrapper.eq("is_hide", 0);
        List<JumiInvoiceList> userList = invoiceListMapper.selectList(queryWrapper);
        if (userList == null) {
            //返回空数组
            return new TableDataInfo<>();
        }
        List<InvoiceUserListResponse> result = new ArrayList<>();
        for (JumiInvoiceList invoiceList : userList) {
            InvoiceUserListResponse invoiceUserListResponse = new InvoiceUserListResponse();
            BeanUtils.copyProperties(invoiceList, invoiceUserListResponse);
            invoiceUserListResponse.setInvoiceTitleId(invoiceList.getId());
            result.add(invoiceUserListResponse);
        }

        dataInfo.setRows(result);
        return dataInfo;
    }

    /**
     * 用户发票抬头列表修改
     *
     * @param invoiceUserListEditRequest
     * @return
     */
    public ResponseResult<Boolean> invoiceEditListUser(InvoiceUserListEditRequest invoiceUserListEditRequest) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        boolean result = false;
        Integer id = invoiceUserListEditRequest.getInvoiceTitleId();
        if (id == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_RED_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_RED_ERROR.getMessage());
        }
        Long uid = invoiceUserListEditRequest.getUid();
        if (uid == null || uid.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_NULL.getMessage());
        }
        Byte headType = invoiceUserListEditRequest.getHeadType();
        if (headType == null || headType.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_HEAD_TYPE_NULL.getMessage());
        }

        Byte isDefault = invoiceUserListEditRequest.getIsDefault();
        if (isDefault == null || isDefault.equals("")) {
            byte isDefaults = 0;
            invoiceUserListEditRequest.setIsDefault(isDefaults);
        } else if (isDefault == 1) {
            invoiceUserListEditRequest.setIsDefault(isDefault);
            //查询出该用户该发票类型以前默认选中数据
            QueryWrapper<JumiInvoiceList> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("head_type", headType);
            queryWrapper.eq("is_default", 1);
            JumiInvoiceList invoiceListOne = invoiceListMapper.selectOne(queryWrapper);
            log.info("用户发票抬头列表修改------【查询出该用户该发票类型以前默认选中数据】:[{}]", JSON.toJSONString(invoiceListOne));
            if (invoiceListOne != null) {
                byte defaults = 0;
                //修改状态为非默认
                invoiceListOne.setIsDefault(defaults);
                int row = invoiceListMapper.updateById(invoiceListOne);
                if (row == 0) {
                    throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_ISDEFUALT.getCode(), InvoiceExceptionEnum.INVOICE_UID_ISDEFUALT.getMessage());
                }
            }
        }
        JumiInvoiceList invoiceList = new JumiInvoiceList();
        BeanUtils.copyProperties(invoiceUserListEditRequest, invoiceList);
        invoiceList.setId(invoiceUserListEditRequest.getInvoiceTitleId());
        log.info("用户发票抬头列表修改------【invoiceList】:[{}]", JSON.toJSONString(invoiceList));
        int row = invoiceListMapper.updateById(invoiceList);
        if (row > 0) {
            //返回 状态
            result = true;
        }
        if (result == true) {
            responseResult.setData(true);
            responseResult.setCode(200);
            responseResult.setMessage("成功");
        } else {
            responseResult.setData(false);
            responseResult.setCode(400);
            responseResult.setMessage("失败");
        }

        return responseResult;
    }

    /**
     * 导出excel
     */
    public ExportExcelCommonResponse<InvoiceExplorResponse> exportExcel(InvoiceExplorRequest request) {
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("application_time");
        List<Integer> invoiceIds = new ArrayList<>();
        if (request.getId() != null) {
            String[] ids = request.getId().split(",");
            for (String id : ids) {
                invoiceIds.add(Integer.valueOf(id));
            }
            queryWrapper.in("id", invoiceIds);
        }
        boolean getOrderNum = true;
        if (request.getOrderNum() != null) {
            queryWrapper.like("order_num", request.getOrderNum());
        } else {
            getOrderNum = false;
        }
        /* 抬头类型： 0,1*/
        boolean getHeadType = true;
        if (request.getHeadType() != null) {
            queryWrapper.like("head_type", request.getHeadType());
        } else {
            getHeadType = false;
        }
        //创建时间
        boolean getBeginTime = true;
        if (request.getBeginTime() != null && !"".equals(request.getBeginTime())) {
            queryWrapper.gt("application_time", request.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        } else {
            getBeginTime = false;
        }

        boolean getEndTime = true;
        if (request.getEndTime() != null && !"".equals(request.getEndTime())) {
            queryWrapper.le("application_time", request.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        } else {
            getEndTime = false;
        }
        /*发票状态*/
        if (request.getInvoiceStatus() != null && !"".equals(request.getInvoiceStatus())) {
            queryWrapper.eq("invoice_status", request.getInvoiceStatus());
        }
        if (!getOrderNum && !getHeadType && !getBeginTime && !getEndTime) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_EXPLODE_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_EXPLODE_ERROR.getMessage());
        }

        List<JumiInvoice> userCashes = invoiceMapper.selectList(queryWrapper);
        log.debug("导出excel------【userCashes】:[{}]", JSON.toJSONString(userCashes));
        if (userCashes.size() == 0) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INFO_NULL.getCode(), InvoiceExceptionEnum.INVOICE_INFO_NULL.getMessage());
        }
        /* 提取所有订单编号，发送订单接口获取后拼接退款金额*/
        List<String> listOrderSn = new ArrayList<>();

        for (JumiInvoice invoiceSn : userCashes) {
            listOrderSn.add(invoiceSn.getOrderNum());
        }
        List<String> listOrders = listOrderSn.stream().distinct().collect(Collectors.toList());

        Map<String, BigDecimal> stringBigDecimalMaps = null;
        log.debug("导出excel------【listOrders】:[{}]", JSON.toJSONString(listOrders));
        if (listOrders.size() > 0) {
            stringBigDecimalMaps = afterService.refundAmount(listOrders);
        }
        log.debug("导出excel------【stringBigDecimalMaps】:[{}]", JSON.toJSONString(stringBigDecimalMaps));
        Map<String, BigDecimal> finalStringBigDecimalMaps = stringBigDecimalMaps;

        List<OrderGoodsNumNameResponse> goodsNamePrice = null;
        log.debug("导出excel------【listOrders】:[{}]", JSON.toJSONString(listOrders));
        if (listOrders.size() > 0) {
            //引入order下返回字段dto
            goodsNamePrice = iorderGoodsService.getGoodsNamePrice(listOrders);
        }
        log.debug("导出excel------【goodsNamePrice】:[{}]", JSON.toJSONString(goodsNamePrice));
        List<OrderGoodsNumNameResponse> finalGoodsNamePrice = goodsNamePrice;

        List<InvoiceExplorResponse> list = new ArrayList<>();
        userCashes.forEach(userCash -> {
            String orderNums = userCash.getOrderNum();
            InvoiceExplorResponse sensitiveExportResponse = new InvoiceExplorResponse();
            BeanUtils.copyProperties(userCash, sensitiveExportResponse);
            log.debug("导出excel------【循环匹配订单详情数组--orderNums】:[{}]", JSON.toJSONString(orderNums));
            log.debug("导出excel------【循环匹配订单详情商品数组】:[{}]", JSON.toJSONString(finalGoodsNamePrice));
            /*循环匹配订单详情数组*/
            List<String> listStr = new ArrayList<>();
            String str = null;
            if (finalGoodsNamePrice.size() > 0) {
                for (OrderGoodsNumNameResponse record : finalGoodsNamePrice) {
                    if (record.getOrderNo().equals(orderNums)) {
                        listStr.add(record.getGoodsName() + "*" + record.getNum());
                    }
                }
                if (listStr.size() > 0) {
                    str = StringUtils.join(listStr, ";");
                }
                sensitiveExportResponse.setInvoiceGoodsList(str);
            }

            if (userCash.getHeadType() == 1) {
                sensitiveExportResponse.setHeadType("企业");
            } else {
                sensitiveExportResponse.setHeadType("个人或事业单位");
            }

            /*退款金额，判断是否存在，根据key提取map的值*/
            log.debug("导出excel------【退款金额】:[{}]", JSON.toJSONString(finalStringBigDecimalMaps));
            if (finalStringBigDecimalMaps.size() > 0 && finalStringBigDecimalMaps.containsKey(orderNums)) {
                sensitiveExportResponse.setRefundAmount(finalStringBigDecimalMaps.get(orderNums));
            }

            list.add(sensitiveExportResponse);
        });
        ExportExcelCommonResponse<InvoiceExplorResponse> response = new ExportExcelCommonResponse<>();
        response.setData(list);
        response.setFileName(System.currentTimeMillis() + ".xlsx");
        return response;
    }

    /**
     * ruiguang提交发票专用
     *
     * @param invoiceAddRequest
     * @return
     */
    public Integer addOrderInvoice(InvoiceAddRequest invoiceAddRequest) {
        Long uid = invoiceAddRequest.getUid();
        if (uid == null || uid.equals("")) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_UID_NULL.getCode(), InvoiceExceptionEnum.INVOICE_UID_NULL.getMessage());
        }
        Integer invoiceId = invoiceAddRequest.getInvoiceId();
        if (invoiceId == null) {
            throw new BaseException(InvoiceExceptionEnum.INVOICE_INVOICE_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_INVOICE_ERROR.getMessage());
        } else {
            //查询该抬头id
            QueryWrapper<JumiInvoiceList> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", invoiceId);
            JumiInvoiceList invoiceListOne = invoiceListMapper.selectOne(queryWrapper);
            log.info("ruiguang提交发票专用------【invoiceListOne】:[{}]", JSON.toJSONString(invoiceListOne));
            if (invoiceListOne == null) {
                throw new BaseException(InvoiceExceptionEnum.INVOICE_INVOICE_ERROR.getCode(), InvoiceExceptionEnum.INVOICE_INVOICE_ERROR.getMessage());
            }
            invoiceAddRequest.setIsDefault(invoiceListOne.getIsDefault());
            invoiceAddRequest.setInvoiceTitle(invoiceListOne.getInvoiceTitle());
            invoiceAddRequest.setHeadType(invoiceListOne.getHeadType());
            invoiceAddRequest.setBankDeposit(invoiceListOne.getBankDeposit());
            invoiceAddRequest.setBankAccount(invoiceListOne.getBankAccount());
            invoiceAddRequest.setBusinessAddress(invoiceListOne.getBusinessAddress());
            invoiceAddRequest.setEnterpriseTel(invoiceListOne.getEnterpriseTel());
            invoiceAddRequest.setDutyParagraph(invoiceListOne.getDutyParagraph());
            invoiceAddRequest.setInvoiceId(invoiceId);
        }
        //实例类
        int ids = 0;
        JumiInvoice invoice = new JumiInvoice();
        BeanUtils.copyProperties(invoiceAddRequest, invoice);
        invoice.setInvoiceAmount(invoiceAddRequest.getInvoiceAmount());
        log.info("ruiguang提交发票专用------【invoice】:[{}]", JSON.toJSONString(invoice));
        Integer insert = invoiceMapper.insert(invoice);
        if (insert > 0) {
            /*插入一条数据并返回该数据id，调用实例类自增id*/
            ids = invoice.getId();
        }
        return ids;
    }


    public ResponseResult<String> redInkOnInvoice(InvoiceOneRequest request) {
        ResponseResult<String> responseResult = new ResponseResult<>();
        QueryThirdCommonRequest queryThirdCommonRequest = new QueryThirdCommonRequest();
        queryThirdCommonRequest.setOrderno(request.getOrderNum());
        String result = nuoNuoUtil.QueryInvoice(queryThirdCommonRequest);
        JSONObject resultResponse = JSON.parseObject(result);
        JSONArray list = resultResponse.getJSONArray("list");
        ThirdCommonParametersRequest<VoidInvoiceRequest> thirdCommonParametersRequest = new ThirdCommonParametersRequest<>();
        VoidInvoiceRequest voidInvoiceRequest = new VoidInvoiceRequest();
        for (Object o : list) {
            voidInvoiceRequest.setFoqqlsh(((JSONObject) o).getString("c_fpqqlsh"));
            voidInvoiceRequest.setFphm(((JSONObject) o).getString("c_fphm"));
            voidInvoiceRequest.setFpdm(((JSONObject) o).getString("c_fpdm"));
        }
        thirdCommonParametersRequest.setOrder(voidInvoiceRequest);
        String voidResult = nuoNuoUtil.voidInvoice(thirdCommonParametersRequest);
        log.info("发票作废接口是:[{}]", JSONObject.toJSONString(voidResult));
        JSONObject jsonObject = JSON.parseObject(voidResult);
        if (jsonObject.getString("status").equals("0000")) {
            QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(JumiInvoice::getOrderNum, request.getOrderNum());
            JumiInvoice invoice = invoiceMapper.selectOne(queryWrapper);
            invoice.setInvoiceStatus(InvoiceStatusEnum.STA_WAIT_REDDDMED.getCode().byteValue());
            invoiceMapper.updateById(invoice);
        }
        responseResult.setData(voidResult);
        return responseResult;
    }

    public String getInvoicePdf(String serialNumber) {
        QueryThirdCommonRequest request = new QueryThirdCommonRequest();
        request.setIdentity("2329CC5F90EDAA82FEE8699FEA1182E24656FEAB5D93A2C6");
        request.setFpqqlsh(serialNumber);
        return nuoNuoUtil.QueryInvoice(request);
    }
}
